Return an array of the number smaller than n


Posted by Christy on 2022-04-19

Description: Write a function named findAllSmall that accepts an array and a number n, returns an array of the number smaller than n.

Answer:

function findAllSmall(arr, n) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      result.push(arr[i]);
    }
  }
  return result;
}

console.log(findAllSmall([1, 2, 3], 10)); // [1, 2, 3]
console.log(findAllSmall([1, 2, 3], 2)); // [1]
console.log(findAllSmall([1, 3, 5, 4, 2], 4)); // [1, 3, 2]

Reflection:

Beware of return in a function, I wrote below at first beginning, it will end the whole function.

function findAllSmall(arr, n) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      return console.log(result.push(arr[i]));
    }
  }
}

findAllSmall([1, 2, 3], 10);

According to the question, below is better

function findAllSmall(arr, n) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      result.push(arr[i]);
    }
  }
  return result;
}

The other answers:

function findAllSmall(arr, n) {
  let i = 0;
  let result = [];
  do {
    if (arr[i] < n) {
      result.push(arr[i]);
    }
    i++;
  } while (i < arr.length);
  return result;
}
function findAllSmall(arr, n) {
  let i = 0;
  let result = [];
  while (i < arr.length) {
    if (arr[i] < n) {
      result.push(arr[i]);
    }
    i++;
  }
  return result;
}









Related Posts

[Week 3] 使用 npm 套件管理系統

[Week 3] 使用 npm 套件管理系統

[day 04] Class & constructor: 吃語法糖別噎到

[day 04] Class & constructor: 吃語法糖別噎到

JavaScript 的 物件 ( Object ) 亂塞一通的學校置物櫃

JavaScript 的 物件 ( Object ) 亂塞一通的學校置物櫃


Comments